﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Data.Common;
using Ice.Toolkit.Data.Entity;
using Ice.Toolkit.Data.ILInvoker;

namespace Ice.Toolkit.Data.Sql
{
    internal class UpdateBuilder<T> : BuilderBase<T> where T : EntityBase<T>, new()
    {
        private String _sqlTemplate = "UPDATE [{0}] SET {1} WHERE [{2}] = @{2}";

        private T _instance;

        public UpdateBuilder(T instance, DataContext context) : base(context) { _instance = instance; }

        public override String Build()
        {
            if (String.IsNullOrEmpty(SQLText))
            {
                var temp = String.Empty;
                var identityColumn = String.Empty;
                var columns = EntityAttribManager.Get<T>().Columns;
                var table = EntityAttribManager.Get<T>().Talbe;

                foreach (var field in columns)
                {
                    if (!field.Value.IsIdentity)
                    {
                        temp += String.Format("[{0}] = @{0}, ", field.Value.DbColumn);
                    }
                    else
                    {
                        identityColumn = field.Value.DbColumn;
                    }

                    AddParameter(field.Key, PropertyAccessor<T>.Get(_instance, field.Key));
                }

                temp = RemoveTail(temp, ",");
                SQLText = String.Format(_sqlTemplate, table.TableName, temp, identityColumn);
            }

            return SQLText;
        }
    }
}
